package com.zhigongtech.tender.sys.service.impl;

import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhigongtech.extension.entry.vo.AccountVo;
import com.zhigongtech.extension.entry.vo.LogVo;
import com.zhigongtech.extension.service.ILogFactoryService;
import com.zhigongtech.tender.sys.entity.LoginLog;
import com.zhigongtech.tender.sys.entity.OperateLog;
import com.zhigongtech.tender.sys.mapper.LoginLogMapper;
import com.zhigongtech.tender.sys.mapper.OperateLogMapper;

import cn.hutool.json.JSONUtil;

@Service
@Transactional
public class LogFactoryServiceImpl implements ILogFactoryService {

	@Autowired
	private OperateLogMapper operateLogMapper;
	
	@Autowired
	private LoginLogMapper loginLogMapper;
	
	@Async("taskExecutor")
	@Override
	public void createOperationLog(LogVo logVo) {
		OperateLog log = warrperVO(logVo);
		operateLogMapper.insert(log);
		// 同时记录登录日志
		if(StringUtils.isBlank(logVo.getReqAccount())
				&& StringUtils.isNotBlank(logVo.getParams())) {
			LoginLog loginLog = createLoginLog(logVo);
			if(loginLog != null) {
				loginLogMapper.insert(loginLog);
			}
		}
	}

	/**
	 * 
	 * @Title: warrperVO   
	 * @Description: 数据转换 
	 * by Alan 2019-06-14 13:53:38
	 * @param logVo
	 * @return      
	 * @return  OperateLog
	 */
	private OperateLog warrperVO(LogVo logVo) {
		OperateLog log = new OperateLog();
		BeanUtils.copyProperties(logVo, log);
		int size = log.getResult().length()>2999?2999:log.getResult().length();
		log.setResult(log.getResult().substring(0, size));
		return log;
	}

	/**
	 * 
	 * @Title: createLoginLog   
	 * @Description: 针对登录日志，单独存放
	 * by Alan 2019-06-14 13:53:49
	 * @param logVo      
	 * @return  void
	 */
	private LoginLog createLoginLog(LogVo logVo) {
		LoginLog login = new LoginLog();
		AccountVo vo = JSONUtil.toBean(JSONUtil.parseArray(logVo.getParams()).get(0).toString(), AccountVo.class);
		if(vo == null) {
			return null;
		}
		login.setLogName(logVo.getMethodName());
		login.setUserId(vo.getAccount());
		login.setLoginIp(logVo.getReqIp());
		login.setLoginDate(Calendar.getInstance().getTime());
		login.setStatus(logVo.getStatus().toString());
		int size = logVo.getResult().length()>999?999:logVo.getResult().length();
		login.setMessage(logVo.getResult().substring(0, size));
		
		return login;
	}
}
